#-*-coding:utf-8-*-
import sys
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from PySide2.QtCore import *
import maya.cmds as cmds
# import abc as cmds
class LightList(QListWidget):
    send_info_Signal=Signal(dict)
    def __init__(self):
        super(LightList, self).__init__()
        self.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.setContextMenuPolicy(Qt.CustomContextMenu)  # 开启自定义右击菜单
        # self.customContextMenuRequested.connect(self.right_menu)
        self.setMaximumWidth(150)
        self.clicked.connect(self._send_info)
        self.data={}

    def init_meshlight(self,data):
        """
          data:  {'geo1':{'aiTranslator':'mesh_light','lightVisible':1},...}
        """
        if data:
            self.clear()
            self.data=data
            for k,v in data.items():
                item=QListWidgetItem()
                item.setText(k)
                item.setSizeHint(QSize(100, 35))
                lightVisible=v['lightVisible']
                item.setTextAlignment(Qt.AlignCenter)
                if lightVisible:
                    item.setBackground(QBrush(QColor('#008000')))
                else:
                    item.setBackground(QBrush(QColor('#696969')))
                self.addItem(item)

    def _send_info(self):
        items=self.selectedItems()
        item=items[0]
        text=item.text()
        info=self.data[text]
        self.send_info_Signal.emit(info)

        select_shapes=[]
        for i in items:
            t=i.text()
            select_shapes.append(t)

        cmds.select(select_shapes)

    def set_lights_visiable(self,b):
        """
        对选择的灯光显示进行设置
        :param b:
        :return:
        """
        items = self.selectedItems()
        if items:
            for i in items:
                text=i.text()
                attr=text+'.lightVisible'
                if b:  #开启
                    cmds.setAttr(attr,1)
                    self.data[text]['lightVisible']=1
                    i.setBackground(QBrush(QColor('#008000')))
                else:
                    cmds.setAttr(attr, 0)
                    self.data[text]['lightVisible']=0
                    i.setBackground(QBrush(QColor('#696969')))

    def set_lights_aiTranslator(self,index):
        """
        对选择的灯光显示进行设置
        :param b:
        :return:
        """
        aiTranslator_list = ['procedural', 'polymesh', 'mesh_light']
        items = self.selectedItems()
        if items:
            for i in items:
                text=i.text()
                attr=text+'.aiTranslator'
                cmds.setAttr(attr, aiTranslator_list[index],typ='string')
                self.data[text]['aiTranslator'] = index
                if index!=2:
                    i.setBackground(QBrush(QColor('#000000')))
                else:
                    i.setBackground(QBrush(QColor('#696969')))


    def set_lights_layer(self,b):
        """
        对选择的灯光显示进行设置
        :param b:
        :return:
        """
        aiTranslator_list = ['procedural', 'polymesh', 'mesh_light']
        items = self.selectedItems()
        if items:
            for i in items:
                text=i.text()
                attr=text+'.lightVisible'


                if b:
                    cmds.editRenderLayerAdjustment(attr)
                    self.data[text]['inlayer'] = 1
                    i.setForeground(QBrush(QColor('#FF4500')))
                else:
                    cmds.editRenderLayerAdjustment(attr, remove=True)
                    self.data[text]['inlayer'] = 0
                    i.setForeground(QBrush(QColor('#F5F5F5')))

    def set_selected(self,name_list):

        for r in range(self.count()):
            item=self.item(r)
            text = item.text()
            if text in name_list:
                item.setSelected(True)
            else:
                item.setSelected(False)

    # def check_repeat(self,artist):
    #     """
    #     检测重名
    #     #parm:artist
    #     """
    #     no_repeat=True
    #     all_count=self.count()
    #     # print('all_count:',all_count)
    #     if all_count>0:
    #         for i in range(all_count):
    #             item=self.item(i)
    #             if item.text() ==artist:
    #                 no_repeat= False
    #                 break
    #             else:
    #                 no_repeat= True
    #     else:
    #         no_repeat= True
    #     return no_repeat

    # def add_artist(self,artist):
    #     if self.check_repeat(artist):
    #         item=QListWidgetItem()
    #         item.setText(artist)
    #         item.setSizeHint(QSize(100, 35))
    #         item.setTextAlignment(Qt.AlignCenter)
    #         item.setBackground(QBrush(QColor('#FFDEAD')))
    #         self.addItem(item)
    #     else:
    #         QMessageBox.information(None,'提示','该人物已添加')

    # def add_department_artists(self,artists):
    #     for i in artists:
    #         if self.check_repeat(i):
    #             item=QListWidgetItem()
    #             item.setText(i)
    #             item.setSizeHint(QSize(100, 35))
    #             item.setTextAlignment(Qt.AlignCenter)
    #             item.setBackground(QBrush(QColor('#FFDEAD')))
    #             self.addItem(item)

    # def right_menu(self):
    #     rMenu = QMenu()
    #     deleteAction=QAction(u'删除',self)
    #     deleteAction.triggered.connect(self._delete_selected)
    #     rMenu.addAction(deleteAction)
    #     rMenu.exec_(QCursor.pos())

    # def _delete_selected(self):
    #     items=self.selectedItems()
    #     # print(items)
    #     if items:
    #         for i in items:
    #             # delete_cg_ids.append(i.data(5)['show_data']['cg_id'])
    #             self.takeItem(self.indexFromItem(i).row())

    # def keyPressEvent(self, event):
    #     if event.key()==Qt.Key_Delete or event.key()==Qt.Key_Backspace:
    #         self._delete_selected()

class MeshLightControl(QDialog):

    def __init__(self):
        super(MeshLightControl, self).__init__()

        self.setWindowTitle('Mesh Light Control')
        self.main_layout=QVBoxLayout()
        self.show_label_layout=QHBoxLayout()
        self.show_label_layout.setAlignment(Qt.AlignCenter)
        self.show_label=QLabel('Mesh Light Control')
        self.show_label_layout.addWidget(self.show_label)
        self.btn_layout=QHBoxLayout()
        self.get_btn=QPushButton(u'获取所有MeshLight几何体')
        self.get_btn.clicked.connect(self._get_all_meshlight)
        self.get_btn.setMinimumHeight(35)
        self.btn_layout.addWidget(self.get_btn)
        self.btn_layout.setAlignment(Qt.AlignRight)
        self.part_layout=QHBoxLayout()
        self.left_layout=QVBoxLayout()
        self.left_list=LightList()#QListWidget()#
        self.left_list.send_info_Signal.connect(self.reset_info)
        self.left_layout.addWidget(self.left_list)
        self.right_layout=QVBoxLayout()
        self.right_layout.setSpacing(50)
        self.right_layout.setAlignment(Qt.AlignTop)
        self.checkbox_layout=QHBoxLayout()
        self.checkbox_layout.setAlignment(Qt.AlignCenter)
        self.checkbox_layout.setContentsMargins(0,50,0,0)
        self.addlayer_check=QCheckBox(u'添加层')
        self.addlayer_check.stateChanged.connect(self._layer_change)
        self.checkbox=QCheckBox(u'开/关')
        self.checkbox.stateChanged.connect(self._check_change)
        self.checkbox.setContentsMargins(50,0,0,0)
        self.checkbox_layout.addWidget(self.addlayer_check)
        self.checkbox_layout.addWidget(self.checkbox)

        self.rev_btn=QPushButton(u'反向选择')
        self.rev_btn.setContentsMargins(0,50,0,0)
        self.rev_btn.clicked.connect(self._rev_select)
        self.translator_layout=QHBoxLayout()
        self.translator_label=QLabel('Arnold Translator:')
        self.translator_menu=QComboBox()
        self.init_menu()
        self.translator_menu.currentIndexChanged.connect(self._translator_change)

        self.translator_layout.addWidget(self.translator_label)
        self.translator_layout.addWidget(self.translator_menu)
        self.right_layout.addLayout(self.checkbox_layout)
        self.right_layout.addLayout(self.translator_layout)
        self.part_layout.addLayout(self.left_layout)
        self.part_layout.addLayout(self.right_layout)

        self.main_layout.addLayout(self.show_label_layout)
        self.main_layout.addLayout(self.btn_layout)
        self.main_layout.addLayout(self.part_layout)
        self.main_layout.addWidget(self.rev_btn)
        self.setLayout(self.main_layout)

    def init_menu(self):
        m_list=['procedural','polymesh','mesh_light']
        self.translator_menu.addItems(m_list)

    def reset_info(self,data):
        if data:
            lightVisible=data['lightVisible']
            aiTranslator=data['aiTranslator']
            inlayer=data['inlayer']
            if inlayer:
                self.addlayer_check.setCheckState(Qt.Checked)
            else :
                self.addlayer_check.setCheckState(Qt.Unchecked)

            if lightVisible:
                self.checkbox.setCheckState(Qt.Checked)
            else:
                self.checkbox.setCheckState(Qt.Unchecked)


            self.translator_menu.setCurrentIndex(aiTranslator)


    def _layer_change(self,status):
        if status==Qt.Checked:
            print(u'加入层')
            self.left_list.set_lights_layer(True)
        else:
            print(u'移除层')
            self.left_list.set_lights_layer(False)

    def _check_change(self,status):
        if status==Qt.Checked:
            print(u'开启')
            self.left_list.set_lights_visiable(True)
        else:
            print(u'关闭')
            self.left_list.set_lights_visiable(False)

    def _translator_change(self,index):
        self.left_list.set_lights_aiTranslator(index)

    def _get_all_meshlight(self):
        """
        获取所有mesh light
        :return:
        """
        aiTranslator_list=['procedural','polymesh','mesh_light']
        data={}  #{'geo1':{'aiTranslator':'mesh_light','lightVisible':1},...}
        allshape = cmds.ls(type='mesh')  # 就是shape名称
        all_mesh_light = []
        # print allmesh
        for shape in allshape:
            at = shape + '.aiTranslator'
            t = cmds.getAttr(at)
            if t == 'mesh_light':
                per_data={}
                all_mesh_light.append(shape)
                vis=shape+'.lightVisible'
                lightVisible=cmds.getAttr(vis)
                per_data['aiTranslator']=2#'mesh_light' #获取的就是mesh_light
                per_data['lightVisible']=lightVisible
                per_data['inlayer']=0
                data[shape]=per_data

        if data:
            cmds.select(all_mesh_light)
            self.left_list.init_meshlight(data)


    def _rev_select(self):
        """
        反向选择
        :return:
        """
        sn = cmds.ls(sl=1)
        sp = cmds.listRelatives(sn, s=1)
        if sp:
            self.left_list.set_selected(sp)


if __name__ == '__main__':
    try:
        t.deleteLater()
    except:
        pass
    t = MeshLightControl()
    try:
        t.create()
        t.show()
    except:
        t.deleteLater()

    # app=QApplication(sys.argv)
    # M=MeshLightControl()
    # # M=LightList()
    # M.show()
    # sys.exit(app.exec_())


